package com.teamwings.ctrls.formCtrls;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teamwings.common.aspect.annotation.FormControl;
import com.teamwings.common.constant.FormConstant;
import com.teamwings.common.vo.Result;
import com.teamwings.ctrls.Field;
import com.teamwings.ctrls.FormComponent;
import com.teamwings.modules.design.vo.FormVo;
import com.teamwings.modules.page.service.IPageService;
import com.teamwings.util.VoUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author wuyc
 */
@FormControl(type = "check_repeat")
@Data
public class CheckRepeat extends FormComponent {

    public CheckRepeat() {
        this.type = "check_repeat";
    }
    
    @Override
    public Result<?> trigger(FormConstant.TRIGGER_TYPE type, IPageService pageService,
                             FormVo formDesignCode, Object paramsData) {
        // 检查重复标题
        /*
            检查 model 的控件，value是否存在同样的内容的记录
            { model: "", target: "", value: "", tableHeadId: "" }
         */
        if (type == FormConstant.TRIGGER_TYPE.CTRL_HANDLER) {
            JSONObject jsonObject = JSON.parseObject(paramsData.toString());
            String model = jsonObject.getString("model");
            String value = jsonObject.getString("value");
            String targetType = jsonObject.getString("target");
            String headId = jsonObject.getString("tableHeadId");
            String tableName = pageService.getTableNameById(headId);
            if (StringUtils.isEmpty(model) || StringUtils.isEmpty(value) || StringUtils.isEmpty(headId)) {
                return null;
            }
            // 查找控件类获取SQL填充格式
            FormComponent emptyComponent = null;
            try {
                emptyComponent = VoUtils.newFormComponentByType(targetType);
            } catch (ClassNotFoundException e) {
                // 这个类型不存在于服务器
                return null;
            }
            emptyComponent.setModel(model);
            Field field = emptyComponent.newField();
            String fieldName = field.getFieldName();

            // 查找是否存在同样的记录
            String sql = "SELECT " + fieldName + " FROM " + tableName + " WHERE " + fieldName + " = "
                    + field.withQuote(value) + " LIMIT 1";
            List<Map> maps = pageService.executeSql(sql);
            return Result.OK(maps.size());
        }
        return null;
    }
}